/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * Wizard.java
 *
 * Created on 12-dic-2011, 20:42:44
 */
package GUI;

import Control.GestorInformes;
import Control.GestorProcesamiento;
import Entidades.informes.Informe;
import com.itextpdf.text.DocumentException;
import com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import javax.swing.ImageIcon;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.swing.plaf.metal.MetalLookAndFeel;

/**
 *
 * @author Cristian Lopez
 */
public class Wizard extends javax.swing.JFrame
{
    private GestorInformes informes;
    private GestorProcesamiento gestorProcesamiento;
    private String criterios[], alternativas[];
    private JFrame padre;

    /** Creates new form Wizard */
    public Wizard(GestorProcesamiento gestorProcesamiento, String criterios[], String alternativas[], JFrame padre)
    {
        this.gestorProcesamiento = gestorProcesamiento;
        this.criterios = criterios;
        this.alternativas = alternativas;
        this.padre = padre;
        try
        {
            UIManager.setLookAndFeel(new NimbusLookAndFeel());
        }
        catch (UnsupportedLookAndFeelException e)
        {
        }
        initComponents();
        this.setTitle("Exportar resultado");
        this.setLocationRelativeTo(null);

        lbl_error.setVisible(false);
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        buttonGroup1 = new javax.swing.ButtonGroup();
        buttonGroup2 = new javax.swing.ButtonGroup();
        pnl_principal = new javax.swing.JPanel();
        btn_finalizar = new javax.swing.JButton();
        btn_cancelar = new javax.swing.JButton();
        jPanel1 = new javax.swing.JPanel();
        jSeparator3 = new javax.swing.JSeparator();
        jSeparator2 = new javax.swing.JSeparator();
        txt_titulo = new javax.swing.JTextField();
        btn_examinar = new javax.swing.JButton();
        jSeparator5 = new javax.swing.JSeparator();
        lbl_tituloInforme = new javax.swing.JLabel();
        lbl_salida = new javax.swing.JLabel();
        lbl_titulo = new javax.swing.JLabel();
        sPnl_tituloAdicional = new javax.swing.JScrollPane();
        txt_descripcion = new javax.swing.JTextArea();
        txt_salida = new javax.swing.JTextField();
        lbl_error = new javax.swing.JLabel();
        lbl_DireccionInforme = new javax.swing.JLabel();
        lbl_tituloInformeAdicional = new javax.swing.JLabel();
        lbl_descripTitulo = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        pnl_principal.setBackground(new java.awt.Color(204, 204, 204));
        pnl_principal.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED));

        btn_finalizar.setText("Finalizar");
        btn_finalizar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btn_finalizarActionPerformed(evt);
            }
        });

        btn_cancelar.setText("Cancelar");
        btn_cancelar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btn_cancelarActionPerformed(evt);
            }
        });

        jSeparator3.setForeground(new java.awt.Color(13, 11, 12));

        jSeparator2.setForeground(new java.awt.Color(13, 11, 12));

        btn_examinar.setText("Examinar");
        btn_examinar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btn_examinarActionPerformed(evt);
            }
        });

        jSeparator5.setForeground(new java.awt.Color(13, 11, 12));

        lbl_tituloInforme.setFont(new java.awt.Font("Arial", 3, 14));
        lbl_tituloInforme.setText("Título");

        lbl_salida.setFont(new java.awt.Font("Times New Roman", 3, 12));
        lbl_salida.setText("Salida: ");

        lbl_titulo.setFont(new java.awt.Font("Times New Roman", 3, 12));
        lbl_titulo.setText("Título: ");

        txt_descripcion.setColumns(20);
        txt_descripcion.setRows(5);
        sPnl_tituloAdicional.setViewportView(txt_descripcion);

        txt_salida.setFont(new java.awt.Font("Times New Roman", 2, 12));

        lbl_error.setFont(new java.awt.Font("Tahoma", 0, 12));
        lbl_error.setForeground(new java.awt.Color(255, 51, 0));
        lbl_error.setText("*La ruta de destino es incorrecta");

        lbl_DireccionInforme.setFont(new java.awt.Font("Arial", 3, 14));
        lbl_DireccionInforme.setText("Directorio de Destino");

        lbl_tituloInformeAdicional.setFont(new java.awt.Font("Arial", 3, 14));
        lbl_tituloInformeAdicional.setText("Descripción");

        lbl_descripTitulo.setText("Escriba el título que tendra el informe. Dicho título, aparecerá al principio del documento.");

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(lbl_DireccionInforme, javax.swing.GroupLayout.PREFERRED_SIZE, 504, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jSeparator5, javax.swing.GroupLayout.PREFERRED_SIZE, 599, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGap(21, 21, 21)
                        .addComponent(lbl_salida)
                        .addGap(18, 18, 18)
                        .addComponent(txt_salida, javax.swing.GroupLayout.PREFERRED_SIZE, 447, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(27, 27, 27)
                        .addComponent(btn_examinar)))
                .addContainerGap(120, Short.MAX_VALUE))
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(lbl_tituloInforme, javax.swing.GroupLayout.PREFERRED_SIZE, 504, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(246, Short.MAX_VALUE))
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jSeparator2, javax.swing.GroupLayout.PREFERRED_SIZE, 599, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(151, Short.MAX_VALUE))
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGap(10, 10, 10)
                        .addComponent(lbl_titulo)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(txt_titulo, javax.swing.GroupLayout.PREFERRED_SIZE, 475, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(lbl_descripTitulo, javax.swing.GroupLayout.DEFAULT_SIZE, 740, Short.MAX_VALUE))
                .addContainerGap())
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(lbl_tituloInformeAdicional, javax.swing.GroupLayout.PREFERRED_SIZE, 504, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(246, Short.MAX_VALUE))
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jSeparator3, javax.swing.GroupLayout.PREFERRED_SIZE, 599, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(151, Short.MAX_VALUE))
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(sPnl_tituloAdicional, javax.swing.GroupLayout.PREFERRED_SIZE, 526, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(224, Short.MAX_VALUE))
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(23, 23, 23)
                .addComponent(lbl_error, javax.swing.GroupLayout.DEFAULT_SIZE, 445, Short.MAX_VALUE)
                .addGap(292, 292, 292))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(lbl_tituloInforme)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jSeparator2, javax.swing.GroupLayout.PREFERRED_SIZE, 9, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(lbl_descripTitulo)
                .addGap(20, 20, 20)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lbl_titulo)
                    .addComponent(txt_titulo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addComponent(lbl_tituloInformeAdicional)
                .addGap(2, 2, 2)
                .addComponent(jSeparator3, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(sPnl_tituloAdicional, javax.swing.GroupLayout.PREFERRED_SIZE, 68, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(27, 27, 27)
                .addComponent(lbl_DireccionInforme)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jSeparator5, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txt_salida, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btn_examinar)
                    .addComponent(lbl_salida))
                .addGap(18, 18, 18)
                .addComponent(lbl_error)
                .addGap(127, 127, 127))
        );

        javax.swing.GroupLayout pnl_principalLayout = new javax.swing.GroupLayout(pnl_principal);
        pnl_principal.setLayout(pnl_principalLayout);
        pnl_principalLayout.setHorizontalGroup(
            pnl_principalLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, pnl_principalLayout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(pnl_principalLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(pnl_principalLayout.createSequentialGroup()
                        .addComponent(btn_finalizar)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(btn_cancelar)))
                .addContainerGap())
        );
        pnl_principalLayout.setVerticalGroup(
            pnl_principalLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(pnl_principalLayout.createSequentialGroup()
                .addContainerGap(16, Short.MAX_VALUE)
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, 369, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addGroup(pnl_principalLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(btn_finalizar, javax.swing.GroupLayout.PREFERRED_SIZE, 46, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btn_cancelar, javax.swing.GroupLayout.PREFERRED_SIZE, 46, javax.swing.GroupLayout.PREFERRED_SIZE)))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(pnl_principal, javax.swing.GroupLayout.DEFAULT_SIZE, 785, Short.MAX_VALUE)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(pnl_principal, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btn_finalizarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_finalizarActionPerformed
        if (txt_salida.getText().isEmpty())
        {
            lbl_error.setVisible(true);
            
        }
        else
        {
            try
            {
                String formato= ".xls";

                String path = (txt_salida.getText().contains(formato)) ? txt_salida.getText() : txt_salida.getText() + formato;
                txt_salida.setText(path);

                if (informes == null)
                {
                    //int sel =  (rbtn_pdf.isSelected()) ? Informe.INFORME_PDF :Informe.INFORME_XLS;
                    int sel = Informe.INFORME_XLS;
                    informes = new GestorInformes(txt_salida.getText(), sel);
                }
                informes.setCriterios(criterios);
                informes.setAlternativas(alternativas);
                informes.setTitulo((txt_titulo.getText().isEmpty()) ? "Informe Promethee" : txt_titulo.getText());
                informes.setMatrizValores(gestorProcesamiento.getMatrizInicial());
                
                informes.setMatrizDiferencias(gestorProcesamiento.getMatrizDiferencias());              
                informes.setMatrizPreferencias(gestorProcesamiento.getMatrizFuncionPreferencia());              
                informes.setMatrizIntensidadPref(gestorProcesamiento.getMatrizIndicePreferencia());
                informes.setFlujosDeSuperacion(gestorProcesamiento.getFlujoSuperacionPositivo(), gestorProcesamiento.getFlujoSuperacionNegativo());
                

                informes.setSubTitulo("", 0);
                if (txt_descripcion.getText() != null && !txt_descripcion.getText().isEmpty())
                {
                    informes.setExplicacion(txt_descripcion.getText(), 0);
                }

                informes.generarInforme(gestorProcesamiento.getPathGrafo());
                Runtime.getRuntime().exec("rundll32 url.dll,FileProtocolHandler " + txt_salida.getText());
                
            }
            catch (DocumentException e)
            {
            }
            catch (FileNotFoundException e)
            {
            }
            catch (IOException e)
            {
            }
            salir();
        }
    }//GEN-LAST:event_btn_finalizarActionPerformed

    private void btn_cancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_cancelarActionPerformed
        salir();
    }//GEN-LAST:event_btn_cancelarActionPerformed

    private void btn_examinarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_examinarActionPerformed
        JFileChooser chooser = new JFileChooser();
        chooser.setCurrentDirectory(new java.io.File(System.getProperty("user.dir")));
        chooser.setDialogTitle("Guardando informe");

        FileNameExtensionFilter filter = null;
        String formato = null;

            filter = new FileNameExtensionFilter("Hoja de Cálculo(*.xls, *.xla, *xlt, *.xlsx)", "xls", "xla", "xlt", "xlsx");
            formato = ".xls";


        chooser.setFileFilter(filter);
        while (true) {
            if (chooser.showSaveDialog(this) == JFileChooser.APPROVE_OPTION) {
                File arch = chooser.getSelectedFile();
                if (arch.exists()) {
                    int confirm = JOptionPane.showConfirmDialog(this, "El archivo " + arch.getName() + " ya existe. ¿Desea Remplazarlo?", "Ya existe un archivo con ese nombre", JOptionPane.INFORMATION_MESSAGE);
                    if (confirm == JOptionPane.CANCEL_OPTION) {
                        break;
                    }
                    if (confirm == JOptionPane.NO_OPTION) {
                        continue;
                    }
                }

                String path = (arch.getAbsolutePath().contains(formato)) ? arch.getAbsolutePath() : arch.getAbsolutePath() + formato;
                txt_salida.setText(path);

                break;
            } else {
                break;
            }
        }
}//GEN-LAST:event_btn_examinarActionPerformed

    private void agregarInformacion(int pos)
    {
        try
        {
            if (informes == null)
            {
                //int sel = (rbtn_pdf.isSelected()) ? Informe.INFORME_PDF : Informe.INFORME_XLS;
                int sel = Informe.INFORME_XLS;
                informes = new GestorInformes(txt_salida.getText(), sel);
            }
            new WizardInfoAdicional(informes, pos).setVisible(true);
        }
        catch (DocumentException e)
        {
        }
        catch (FileNotFoundException e)
        {
        }
        catch (IOException e)
        {
        }
    }

    private void modificarInformacion(int pos)
    {
        new WizardInfoAdicional(informes, pos, informes.getSubtitulo(pos), informes.getExplicacion(pos)).setVisible(true);
    }

    private void quitarInformacion(int pos)
    {
        informes.setSubTitulo("", pos);
        informes.setExplicacion("", pos);
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btn_cancelar;
    private javax.swing.JButton btn_examinar;
    private javax.swing.JButton btn_finalizar;
    private javax.swing.ButtonGroup buttonGroup1;
    private javax.swing.ButtonGroup buttonGroup2;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JSeparator jSeparator2;
    private javax.swing.JSeparator jSeparator3;
    private javax.swing.JSeparator jSeparator5;
    private javax.swing.JLabel lbl_DireccionInforme;
    private javax.swing.JLabel lbl_descripTitulo;
    private javax.swing.JLabel lbl_error;
    private javax.swing.JLabel lbl_salida;
    private javax.swing.JLabel lbl_titulo;
    private javax.swing.JLabel lbl_tituloInforme;
    private javax.swing.JLabel lbl_tituloInformeAdicional;
    private javax.swing.JPanel pnl_principal;
    private javax.swing.JScrollPane sPnl_tituloAdicional;
    private javax.swing.JTextArea txt_descripcion;
    private javax.swing.JTextField txt_salida;
    private javax.swing.JTextField txt_titulo;
    // End of variables declaration//GEN-END:variables

    private void salir()
    {
        try
        {
            UIManager.setLookAndFeel(new MetalLookAndFeel());
        }
        catch (UnsupportedLookAndFeelException e)
        {
        }
        if (padre instanceof Principal)
        {
            File dir = new File("." + File.separator + "res" + File.separator + "tmp");
            if (dir.exists())
            {
                File[] archivos = dir.listFiles();
                for (int i = 0; i < archivos.length; i++)
                {
                    archivos[i].delete();
                }
                dir.delete();
            }
        }
        padre.setVisible(true);
        this.dispose();
    }
}
